<template>
  <div class="lobby">
    <el-card class="lobby-card">
      <div class="lobby-header">
        <h1>房间大厅</h1>
        <div class="lobby-actions">
          <el-button type="success" @click="showCreateDialog = true">创建房间</el-button>
        </div>
      </div>
      <el-table
        :data="rooms"
        style="width: 100%; margin-top: 20px;"
        stripe
        highlight-current-row
        border
      >
        <template #empty>
          <div class="custom-empty">暂无房间</div>
        </template>
        <el-table-column prop="id" label="房间ID" width="180" />
        <el-table-column prop="roomName" label="房间名称" />
        <el-table-column prop="gameState" label="游戏状态" width="100" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openJoinDialog(scope.row.id, scope.row.roomName, scope.row.gameState)">加入</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog v-model="showCreateDialog" title="创建房间" width="350px">
      <el-input
        v-model="newRoomName"
        placeholder="请输入房间名称"
        maxlength="20"
        show-word-limit
        clearable
      />
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createRoom">创建</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showJoinDialog" title="输入昵称" width="350px">
      <el-input v-model="playerName" placeholder="请输入你的昵称" maxlength="12" show-word-limit clearable @input="onPlayerNameInput" />
      <template #footer>
        <el-button @click="showJoinDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmJoinRoom">加入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { getRoom, addRoom } from '../api/room'
import { ElMessage } from 'element-plus'
const router = useRouter()

const { proxy } = getCurrentInstance()!
const $socket = (proxy as any).$socket

const showCreateDialog = ref(false)
const newRoomName = ref('')
const roomMakerName = ref('')
const newRoomNum = ref<number | null>(null)
const showJoinDialog = ref(false)
const joinRoomId = ref<string>('')
const joinRoomName = ref<string>('')
const playerName = ref('')

// 房间列表数据
const rooms = ref<any[]>([])

// 打开加入房间弹窗
function openJoinDialog(id: string, roomName: string, gameState: string) {
  if (gameState === '游戏中') {
    ElMessage.warning('该房间正在游戏中，无法加入')
    return
  }
  joinRoomId.value = id
  joinRoomName.value = roomName
  showJoinDialog.value = true
}

function onPlayerNameInput(val: string) {
  // 去除所有空格
  playerName.value = val.replace(/\s+/g, '')
}

function sendWhenReady(message: any) {
  if ($socket && $socket.readyState === 1) {
    $socket.send(JSON.stringify(message))
  } else if ($socket) {
    const handler = () => {
      $socket.send(JSON.stringify(message))
      $socket.removeEventListener('open', handler)
    }
    $socket.addEventListener('open', handler)
  } else {
    console.error('WebSocket 未初始化')
  }
}

async function confirmJoinRoom() {
  if (!playerName.value) {
    ElMessage.error('请输入昵称')
    return
  }
  // 存到 sessionStorage
  sessionStorage.setItem('playerName', playerName.value)

  sendWhenReady({
    event: 'joinRoom',
    data: { roomId: joinRoomId.value, playerName: playerName.value }
  })

  router.push({
      name: `room`,
      params: { roomId: joinRoomId.value,roomName:joinRoomName.value}
    })
}

async function fetchRoomList() {
  const res = await getRoom() 
  rooms.value = res.data.data
}

async function createRoom() {
  if (!newRoomName.value) return
  await addRoom(newRoomName.value, '未开始')
  showCreateDialog.value = false
  newRoomName.value = ''
  newRoomNum.value = null
  fetchRoomList()
}

onMounted(() => {
  fetchRoomList()
})
</script>

<style scoped>
.lobby {
  min-height: 100vh;
  background: linear-gradient(135deg, #e0e7ef 0%, #f8fafc 100%);
  display: flex;
  justify-content: center;
}

.lobby-card {
  width: 900px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.12);
  padding: 40px 32px 32px 32px;
  background: #fff;
  border: none;
}

.lobby-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.lobby-header h1 {
  font-size: 2.6rem;
  font-weight: 800;
  margin: 0;
  color: #222;
  letter-spacing: 2px;
}

.lobby-actions .el-button {
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: background 0.2s, box-shadow 0.2s;
}
.lobby-actions .el-button + .el-button {
  margin-left: 16px;
}
.lobby-actions .el-button:hover {
  filter: brightness(1.08);
  box-shadow: 0 4px 16px rgba(0,0,0,0.10);
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  background: #fafbfc;
}
.el-table th {
  background: #f0f2f5 !important;
  color: #333;
  font-weight: 700;
  font-size: 1.05rem;
}
.el-table tr {
  transition: background 0.2s;
}
.el-table tr:hover {
  background: #e6f7ff !important;
}
.el-table__empty-block {
  white-space: nowrap;      /* 不换行 */     /* 居中 */
  font-size: 1.2rem;
  color: #bbb;
  padding: 40px 0;
}

.el-dialog {
  border-radius: 16px !important;
  box-shadow: 0 8px 32px rgba(0,0,0,0.14) !important;
}
.el-dialog__footer {
  text-align: right;
}
.el-dialog .el-button {
  border-radius: 8px;
  min-width: 80px;
  margin-left: 12px;
}
.custom-empty {
  color: #bbb;
  font-size: 1.2rem;
  text-align: center;
  padding: 40px 0;
  white-space: nowrap;
}
</style> 